package cn.conac.rc.ofs.service;

import cn.conac.rc.framework.jpa.Restrictions;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import cn.conac.rc.ofs.entity.VOrgPreSubEntity;
import cn.conac.rc.ofs.repository.VOrgPreSubRepository;
import cn.conac.rc.ofs.vo.VOrgPreSubVo;
import cn.conac.rc.framework.jpa.Criteria;
import cn.conac.rc.framework.service.GenericService;

/**
 * VOrgPreSubService类
 *
 * @author serviceCreator
 * @date 2016-12-14
 * @version 1.0
 */
@Service
public class VOrgPreSubService extends GenericService<VOrgPreSubEntity, Integer> {

	@Autowired
	private VOrgPreSubRepository repository;

	/**
	 * 计数查询
	 * @param vo
	 * @return 计数结果
	 */
	public long count(VOrgPreSubVo vo){
		return super.count(this.createCriteria(vo));
	}

	/**
	 * 动态查询，分页，排序查询
	 * @param vo
	 * @return Page
	 * @throws Exception
	 */
	public Page<VOrgPreSubEntity> list(VOrgPreSubVo vo) throws Exception {
		try {
			Sort sort = new Sort(Direction.DESC, "updateTime");
			Pageable pageable = new PageRequest(vo.getPage(), vo.getSize(), sort);
			Criteria<VOrgPreSubEntity> dc = this.createCriteria(vo);
			return repository.findAll(dc, pageable);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 动态查询条件
	 * @param param
	 * @return Criteria
	 */
	private Criteria<VOrgPreSubEntity> createCriteria(VOrgPreSubVo param) {
		Criteria<VOrgPreSubEntity> dc = new Criteria<VOrgPreSubEntity>();
		// 根据地区ID检索
		if(StringUtils.isNotBlank(param.getAreaId())){
			dc.add(Restrictions.eq("areaId",param.getAreaId(),true));
		}
		// 根据 名称搜索
		if(StringUtils.isNotBlank(param.getName())){
			dc.add(Restrictions.like("name",param.getName(),true));
		}
		// 部门类型
		if(StringUtils.isNotBlank(param.getType())){
			dc.add(Restrictions.eq("type",param.getType(),true));
		}
		// 部门ID
		if(null  !=param.getOrgId()){
			dc.add(Restrictions.eq("orgId",param.getOrgId(),true));
		}
		// 用户ID
		if (param.getUserId() != null) {
			dc.add(Restrictions.eq("userId", param.getUserId(), true));
		}
		return dc;
	}

}
